layui.use(["table", "jquery", "layer", "form"], function () {
  var table = layui.table;
  var form = layui.form;
  var layer = layui.layer;
  var $ = layui.jquery;

  table.render({
    elem: "#test",
    height: layui_table_view__height,
    toolbar: "#toolbarDemo",
    defaultToolbar: ["filter", "print"],
    id: "top_table",
    data: [],
    parseData: function (res) {
      //res 即为原始返回的数据
      // console.log(res);
      return {
        code: 0, //解析接口状态
        msg: "成功", //解析提示文本
        count: res.total, //解析数据长度
        data: res.rows, //解析数据列表
      };
    },
    cols: [
      [
        {field: 'indent', width: 80, title: 'ID', sort: true, hide: true}
        , {field: 'fileNumber', width: 180, title: '档号', sort: true}
        , {field: 'fondNumber', title: '全宗号', sort: true}
        , {field: 'archiveCode', title: '档案馆代码', hide: true}
        , {field: 'recodeNumber', title: '档案号', hide: true}
        , {field: 'certNumber', title: '证字号', event: 'setSign'}
        , {field: 'correctTitle', title: '正题名',hide: true}
        , {field: 'maleGender', title: '男性别', hide: true}
        , {field: 'maleName', title: '男姓名'}
        , {field: 'maleIdNumber', title: '男身份证', hide: true}
        , {field: 'malebirth', title: '男出生日期', hide: true}
        , {field: 'maleOrigMaritalStatus', title: '男方原婚姻状态', hide: true}
        , {field: 'maleCertType', title: '男方证件类型', hide: true}
        , {field: 'maleIdType', title: '男方身份类型', hide: true}
        , {field: 'maleNationality', title: '男方国籍', hide: true}
        , {field: 'maleNation', title: '男方民族', hide: true}
        , {field: 'maleLocation', title: '男方常住户口所在地', hide: true}
        , {field: 'maleCertNumber', title: '男方证件印制号', hide: true}
        , {field: 'femaleGender', title: '女性别', hide: true}
        , {field: 'femaleName', title: '女姓名'}
        , {field: 'femaleIdNumbe', title: '女身份证号', hide: true}
        , {field: 'femalebirth', title: '女出生日期', hide: true}
        , {field: 'femaleOrigMaritalStatus', title: '女方原婚姻状态', hide: true}
        , {field: 'femaleCertType', title: '女方证件类型', hide: true}
        , {field: 'femaleIdType', title: '女方身份类型', hide: true}
        , {field: 'femaleNationality', title: '女方国籍', hide: true}
        , {field: 'femaleNation', title: '女方民族', hide: true}
        , {field: 'femaleLocation', title: '女方常住户口所在地', hide: true}
        , {field: 'femaleCertNumber', title: '女方证件印制号', hide: true}
        , {field: 'registAuthority', title: '登记机关', hide: true}
        , {field: 'origRegistAuthority', title: '原登记机关', hide: true}
        , {field: 'origRegistDate', title: '原登记日期', hide: true}
        , {field: 'underAgency', title: '承办机关', hide: true}
        , {field: 'registName', title: '登记员姓名', hide: true}
        , {field: 'delNot', title: '是否删除', hide: true}
        , {field: 'maritalCertRemark', title: '结婚证备注', hide: true}
        , {field: 'divorceCertRemark', title: '离婚证备注', hide: true}
        , {field: 'origMaritalRegistDate', title: '原结婚登记日期', hide: true}
        , {field: 'otherRemark', title: '其他备注', hide: true}
        , {field: 'businessType', title: '业务类型', hide: true}
        , {field: 'year', title: '年度', hide: true}
        , {field: 'marryDate', title: '结婚日期', hide: true}
        , {field: 'registDate', title: '登记日期', hide: true}
        , {field: 'maleMarryType', title: '男方结婚类型', hide: true}
        , {field: 'femaleMarryType', title: '女方结婚类型', hide: true}
        ,

        { fixed: "right", title: "操作", toolbar: "#barDemo", width: 80 },
      ],
    ],
    page: {
      //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
      limit: 15, //一页显示多xx少条
      limits: [10, 15, 20, 25, 30], //每页条数的选择项
      last: "尾页", //不显示尾页
    },
  });

  //头工具栏事件
  table.on("toolbar(test)", function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
      case "search_Test":
        let tr_arr = $(
          "[lay-id='top_table'] .layui-table-body.layui-table-main tr"
        );
        // console.log(tr_arr);
        let search_value = $("#test_Reload__input").val();
        search_value = search_value.trim();
        // console.log(tr_arr,search_value)

        for (let index = 0; index < tr_arr.length; index++) {
          let text_arr = [];

          let tr_index = tr_arr.eq(index);

          for (let inner = 0; inner < tr_index.children().length; inner++) {
            let td_index = tr_index.children().eq(inner).text();
            td_index = td_index.trim();
            text_arr.push(td_index);
          }

          // console.log(text_arr);
          let have = false;
          for (let index = 0; index < text_arr.length; index++) {
            const text = text_arr[index];

            if (text.indexOf(search_value) > -1) {
              have = true;
            }

            if (index + 1 == text_arr.length && !have) {
              tr_index.css("display", "none");
            } else {
              tr_index.css("display", "");
            }
          }
        }

        break;
      case "showAll":
        layer.confirm("是否显示全部？", { icon: 3, title: "提示" }, function (
          index
        ) {
          let tr_arr = $(
            "[lay-id='top_table'] .layui-table-body.layui-table-main tr"
          );
          for (let index = 0; index < tr_arr.length; index++) {
            const tr_index = tr_arr.eq(index);
            tr_index.css("display", "");
          }
          layer.close(index);
        });
        break;
    }
  });

  //监听行工具事件
  table.on("tool(test)", function (obj) {
    var data = obj.data;
    switch (obj.event) {
      case "edit":
        // console.log(data);
        INIT_DATA = {};
        // 编辑框的默认值
        INIT_DATA = {
          indent: data.indent,
          fileNumber: data.fileNumber,
          fondNumber: data.fondNumber,
          archiveCode: data.archiveCode,
          recodeNumber: data.recodeNumber,
          certNumber: data.certNumber,
          correctTitle: data.correctTitle,
          maleGender: data.maleGender,
          maleName: data.maleName,
          maleIdNumber: data.maleIdNumber,
          malebirth: data.malebirth,
          maleOrigMaritalStatus: data.maleOrigMaritalStatus,
          maleCertType: data.maleCertType,
          maleIdType: data.maleIdType,
          maleNationality: data.maleNationality,
          maleNation: data.maleNation,
          maleLocation: data.maleLocation,
          maleCertNumber: data.maleCertNumber,
          femaleGender: data.femaleGender,
          femaleName: data.femaleName,
          femaleIdNumbe: data.femaleIdNumbe,
          femalebirth: data.femalebirth,
          femaleOrigMaritalStatus: data.femaleOrigMaritalStatus,
          femaleCertType: data.femaleCertType,
          femaleIdType: data.femaleIdType,
          femaleNationality: data.femaleNationality,
          femaleNation: data.femaleNation,
          femaleLocation: data.femaleLocation,
          femaleCertNumber: data.femaleCertNumber,
          registAuthority: data.registAuthority,
          origRegistAuthority: data.origRegistAuthority,
          origRegistDate: data.origRegistDate,
          underAgency: data.underAgency,
          registName: data.registName,
          delNot: data.delNot,
          maritalCertRemark: data.maritalCertRemark,
          origMaritalRegistDate: data.origMaritalRegistDate,
          otherRemark: data.otherRemark,
          businessType: data.businessType,
          year: data.year,
          marryDate: data.marryDate,
          registDate: data.registDate,
          maleMarryType: data.maleMarryType,
          femaleMarryType: data.femaleMarryType,
          divorceCertRemark: data.divorceCertRemark
        };
        if (data.type == 0) {
          let editIndex = layer.open({
            type: 1,
            title: "编辑",
            maxmin: true,
            area: ["500px","500px"],
            content: TABLE_HTML.top_tableEditHtml,
            success: function () {
              form.val("popFromId", INIT_DATA);
            },
          });
          $(document).one("click", "#top_test_edit__form", function () {
            let d = {};
            let t = $("#popForm [name]").serializeArray();
            $.each(t, function () {
              d[this.name] = this.value;
            });

            if (!d.fileNumber || !d.fileTitle) {
              layer.msg("档案号或文件标题不能为空！");
              return false;
            }
            // console.log(d);
            $.ajax({
              url: "/file",
              type: "PUT",
              data: d,
              success: function (rep) {
                console.log(rep);
                if (rep.status == 200) {
                  layer.msg("编辑成功！");
                  table.reload(
                    "top_table",
                    {
                      page: {
                        curr: 1, //重新从第 1 页开始
                      },
                      where: {},
                    },
                    "data"
                  );
                  layer.close(editIndex);
                } else {
                  layer.msg("编辑失败！");
                  console.error(rep);
                }
              },
              error: function (error) {
                console.warn(error.statusText);
              },
            });
            return false;
          });
          $(document).one("click", "#top_test_edit__form_init", function () {
            layer.confirm("是否重置？", function (index) {
              form.val("popFromId", INIT_DATA);
              layer.close(index);
            });
          });
        } else if (data.type == 1) {
          let bottom_editIndex = layer.open({
            type: 1,
            title: "编辑",
            maxmin: true,
            area: ["500px","500px"],
            content: TABLE_HTML.bottom_tableEditHtml,
            success: function () {
              form.val("popFromId-2", INIT_DATA);
            },
          });
          $(document).one("click", "#bottom_test_edit__form", function () {
            let d = {};
            let t = $("#popForm-2 [name]").serializeArray();
            $.each(t, function () {
              d[this.name] = this.value;
            });
            // console.log(d);

            if (!d.levelNumber || !d.fileTitle) {
              layer.msg("文件级档案号或文件标题不能为空！");
              return false;
            }
            $.ajax({
              url: "/file",
              type: "PUT",
              data: d,
              success: function (rep) {
                console.log(rep);
                if (rep.status == 200) {
                  layer.msg("编辑成功！");
                  table.reload(
                    "bottom_table",
                    {
                      page: {
                        curr: 1, //重新从第 1 页开始
                      },
                      url: "/file/dire/fileNumber/" + current_fileNumber,
                      where: {},
                    },
                    "data"
                  );
                  layer.close(bottom_editIndex);
                } else {
                  layer.msg("编辑失败！");
                  console.error(rep);
                }
              },
              error: function (error) {
                console.warn(error.statusText);
              },
            });

            return false;
          });
          $(document).one("click", "#bottom_test_edit__form_init", function () {
            layer.confirm("是否重置？", function (index) {
              form.val("popFromId-2", INIT_DATA);
              layer.close(index);
            });
          });
        }
        break;
      case "del":
        layer.confirm("确认删除？", function (index) {
          $.ajax({
            url: "/file/" + data.id,
            type: "DELETE",
            success: function (rep) {
              // console.log(rep);
              if (rep.status == 200) {
                layer.msg("删除成功！");
                table.reload(
                  "top_table",
                  {
                    page: {
                      curr: 1, //重新从第 1 页开始
                    },
                    where: {},
                  },
                  "data"
                );
              } else {
                layer.msg("编辑失败！");
                console.error(rep);
              }
            },
            error: function (error) {
              console.warn(error.statusText);
            },
          });
          layer.close(index);
        });
        break;
      case "view":
        if (data.type == 0) {
          current_fileNumber = data.fileNumber;
          table.reload(
            "bottom_table",
            {
              url: "/file/dire/fileNumber/" + current_fileNumber,
              page:{
                curr:1
              }
            },
            "data"
          );
        }
        if (data.type == 1) {
          if (!data.including) {
            layer.msg("无文件");
            return;
          }
          var url = data.filePath.trim();
          var host = location.host;
  
          layer.open({
            type: 1,
            title: data.levelNumber,
            maxmin: true,
            area: ["50%", "100%"],
            content: `<iframe src="/js/web/viewer.html?file=http://${host}${url}"frameborder="0" style="width:100%;height:99%;"></iframe>`,
          });
        }
        break;
    }
  });
});

// 下表格
layui.use(["table", "jquery", "layer", "form"], function () {
  var table = layui.table;
  var form = layui.form;
  var layer = layui.layer;
  var $ = layui.jquery;

  table.render({
    elem: "#test-2",
    id: "bottom_table",
    toolbar: "#toolbarDemo-2",
    height: layui_table_view__height,
    defaultToolbar: ["filter", "print"],
    data:[],
    parseData: function (res) {
      //res 即为原始返回的数据
      // console.log(res);
      return {
        code: 0, //解析接口状态
        msg: "成功", //解析提示文本
        count: res.length, //解析数据长度
        data: res, //解析数据列表
      };
    },
    cols: [
      [
        { field: "id", width: 80, title: "ID", sort: true, hide: true },
        { field: "levelNumber", width: 200, title: "文件级档号", sort: true ,hide :true},
        { field: "categoryName", title: "分类名称", hide: true },
        { field: "fileCategory", title: "档案类别", hide: true },
        { field: "fondName", title: "全宗名称", hide: true },
        { field: "storagePeriodCode", title: "保管期限代码", hide: true },
        { field: "secretLevel", title: "密级", hide: true },
        { field: "subjectHeading", title: "文件标题" },
        { field: "organization", title: "组织机构", hide: true },
        { field: "remarks", title: "备注", hide: true },
        { field: "fondNumber", title: "全宗号", hide: true },
        { field: "filesNumber", title: "案卷号", hide: true },
        { field: "person", width: 180, title: "责任者" },
        { field: "annex", title: "附件", hide: true },
        { field: "pageNumber", title: "张页号" },
        { field: "problem", title: "问题", hide: true },
        { field: "storageTime", title: "保管期限", hide: true, sort: true },
        { field: "note", title: "附注", hide: true },
        { field: "volumeNumber", title: "卷内顺序号", hide: true },
        { field: "categoryNumber", title: "分类号", hide: true },
        // { field: "writingDate", title: "成文日期", sort: true },
        { fixed: "right", title: "操作", toolbar: "#barDemo-2", width: 80 },
      ],
    ],
    page: {
      //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
      limit: 15, //一页显示多xx少条
      limits: [10, 15, 20, 25, 30], //每页条数的选择项
      last: "尾页", //不显示尾页
    },
  });

  //头工具栏事件
  table.on("toolbar(test-2)", function (obj) {
    switch (obj.event) {
      case "search_Test_2":
        let tr_arr = $(
          "[lay-id='bottom_table'] .layui-table-body.layui-table-main tr"
        );
        let search_value = $("#test_Reload__input_2").val();
        search_value = search_value.trim();
        // console.log(tr_arr,search_value);
        for (let index = 0; index < tr_arr.length; index++) {
          let text_arr = [];

          let tr_index = tr_arr.eq(index);

          for (let inner = 0; inner < tr_index.children().length; inner++) {
            let td_index = tr_index.children().eq(inner).text();
            td_index = td_index.trim();
            text_arr.push(td_index);
          }

          // console.log(text_arr);
          let have = false;
          for (let index = 0; index < text_arr.length; index++) {
            const text = text_arr[index];

            if (text.indexOf(search_value) > -1) {
              have = true;
            }

            if (index + 1 == text_arr.length && !have) {
              tr_index.css("display", "none");
            } else {
              tr_index.css("display", "");
            }
          }
        }
        break;
      case "showAll_2":
        layer.confirm("是否显示全部？", { icon: 3, title: "提示" }, function (
          index
        ) {
          table.reload(
            "bottom_table",
            {
              page: {
                curr: 1, //重新从第 1 页开始
              },
              url: "/file/dire/fileNumber/" + current_fileNumber,
              where: {},
            },
            "data"
          );
        });
        break;
      case "addNew_2":
        let editIndex = layer.open({
          type: 1,
          title: "添加",
          maxmin: true,
          area: ["500px","500px"],
          content: TABLE_HTML.bottom_add_tableEditHtml,
        });
        $(document).one("click", "#bottom_add_test_edit__form", function () {
          let d = {};
          let t = $("#popForm-4 [name]").serializeArray();
          $.each(t, function () {
            d[this.name] = this.value;
            if (d[this.name] == "") {
              delete d[this.name];
            }
          });
          d.fileNumber = current_fileNumber;
          d.type = 1;
          // console.log(d);

          if (!d.levelNumber || !d.fileTitle) {
            layer.msg("文件级档案号或文件标题不能为空！");
            return false;
          }

          $.ajax({
            url: "/file",
            type: "POST",
            data: d,
            success: function (rep) {
              console.log(rep);
              if (rep.status == 200) {
                layer.msg("添加成功！");
                table.reload(
                  "bottom_table",
                  {
                    page: {
                      curr: 1, //重新从第 1 页开始
                    },
                    url: "/file/dire/fileNumber/" + current_fileNumber,
                    where: {},
                  },
                  "data"
                );
                layer.close(editIndex);
                return false;
              } else {
                layer.msg("添加失败！");
                console.error(rep);
                return false;
              }
            },
            error: function (error) {
              console.warn(error.statusText);
            },
          });
          return false;
        });
        $(document).one(
          "click",
          "#bottom_add_test_edit__form_init",
          function () {
            layer.confirm("是否重置？", function (index) {
              // form.val("popFromId-3", INIT_DATA);
              document.getElementById("popForm-4").reset();
              layer.close(index);
            });
          }
        );
        break;
    }
  });

  //监听行工具事件
  table.on("tool(test-2)", function (obj) {
    var data = obj.data;
    switch (obj.event) {
      case "edit-2":
        // console.log(data);
        INIT_DATA = {};
        // 编辑框的默认值
        INIT_DATA = {
          id: data.id,
          levelNumber: data.levelNumber,
          categoryName: data.categoryName,
          fileCategory: data.fileCategory,
          fondName: data.fondName,
          storagePeriodCode: data.storagePeriodCode,
          secretLevel: data.secretLevel,
          fileTitle: data.fileTitle,
          organization: data.organization,
          remarks: data.remarks,
          fondNumber: data.fondNumber,
          filesNumber: data.filesNumber,
          person: data.person,
          annex: data.annex,
          pageNumber: data.pageNumber,
          problem: data.problem,
          storageTime: data.storageTime,
          note: data.note,
          volumeNumber: data.volumeNumber,
          categoryNumber: data.categoryNumber,
          writingDate: data.writingDate,
        };
        let bottom_editIndex = layer.open({
          type: 1,
          title: "编辑",
          maxmin: true,
          area: ["500px","500px"],
          content: TABLE_HTML.bottom_tableEditHtml,
          success: function () {
            form.val("popFromId-2", INIT_DATA);
          },
        });
        $(document).one("click", "#bottom_test_edit__form", function () {
          let d = {};
          let t = $("#popForm-2 [name]").serializeArray();
          $.each(t, function () {
            d[this.name] = this.value;
          });
          // console.log(d);

          if (!d.levelNumber || !d.fileTitle) {
            layer.msg("文件级档案号或文件标题不能为空！");
            return false;
          }
          $.ajax({
            url: "/file",
            type: "PUT",
            data: d,
            success: function (rep) {
              console.log(rep);
              if (rep.status == 200) {
                layer.msg("编辑成功！");
                table.reload(
                  "bottom_table",
                  {
                    page: {
                      curr: 1, //重新从第 1 页开始
                    },
                    url: "/file/dire/fileNumber/" + current_fileNumber,
                    where: {},
                  },
                  "data"
                );
                layer.close(bottom_editIndex);
              } else {
                layer.msg("编辑失败！");
                console.error(rep);
              }
            },
            error: function (error) {
              console.warn(error.statusText);
            },
          });

          return false;
        });
        $(document).one("click", "#bottom_test_edit__form_init", function () {
          layer.confirm("是否重置？", function (index) {
            form.val("popFromId-2", INIT_DATA);
            layer.close(index);
          });
        });
        break;
      case "del-2":
        layer.confirm("确认删除？", function (index) {
          $.ajax({
            url: "/file/" + data.id,
            type: "DELETE",
            success: function (rep) {
              console.log(rep);
              if (rep.status == 200) {
                layer.msg("删除成功！");

                table.reload(
                  "bottom_table",
                  {
                    url: "/file/dire/fileNumber/" + current_fileNumber,
                    where: {},
                  },
                  "data"
                );
                layer.close(index);
              } else {
                layer.msg("编辑失败！");
                console.error(rep);
              }
            },
            error: function (error) {
              console.warn(error.statusText);
            },
          });
          layer.close(index);
        });
        break;
      case "view-2":
        if (!data.including) {
          layer.msg("无文件");
          return;
        }
        var url = data.filePath.trim();
        var host = location.host;

        layer.open({
          type: 1,
          title: data.levelNumber,
          maxmin: true,
          area: ["50%", "100%"],
          content: `<iframe src="/web/viewer.html?file=http://${host}${url}"frameborder="0" style="width:100%;height:99%;"></iframe>`,
        });
        break;
    }
  });
});
